package com.example.myapplication.socket;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class TcpClient extends Thread {

    private String TAG = "TcpClient";
    private String serverIP = "192.168.88.141";
    private int serverPort = 1234;
    private PrintWriter pw;
    private InputStream is;
    private DataInputStream dis;
    private boolean isRun = true;
    private Socket socket = null;
    byte buff[] = new byte[4096];
    private String rcvMsg;
    private int rcvLen;
    private Handler handler;

    public TcpClient(String ip, int port, Handler handler) {
        this.serverIP = ip;
        this.serverPort = port;
        this.handler = handler;
    }



    @Override
    public void run() {
        try {

            while (true) {
                //发送数据

                socket = new Socket(serverIP,serverPort);
                OutputStream OutStream = socket.getOutputStream();
                OutStream.write("start".getBytes());
                OutStream.flush();
                byte[] buffer = new byte[10000];
                InputStream inputStream = socket.getInputStream();
                DataInputStream input = new DataInputStream(inputStream);
                int length = input.read(buffer);
                String Msg = new String(buffer, 0, length, "UTF-8");
                Log.d("客户端接收到的数据：",Msg);
                Message msg = new Message();
                Log.d(TAG, "run: " + Msg);
                msg.what = 0x128;
                msg.obj = Msg;
                handler.sendMessage(msg);

            }
        } catch (Exception ex) {
            Log.e("TCP发送接收:", ex.toString());
            ex.printStackTrace();
        }


    }


}
